package com.dlgcy.xinlang_weibo;

import java.io.IOException;

import weibo4j.Oauth;
import weibo4j.Users;
import weibo4j.http.AccessToken;
import weibo4j.model.User;
import weibo4j.model.WeiboException;
import weibo4j.util.BareBonesBrowserLaunch;

import com.dlgcy.weibo.ConfigUtil;

public class OAuth4Code {
	static String FILE_PATH = ConfigUtil.FILE_PATH;

	public static Oauth authorize() throws WeiboException, IOException {
		Oauth oauth = new Oauth();
		String scope = "";
		String state = "";
		boolean forcelogin = true;
		BareBonesBrowserLaunch.openURL(oauth.authorize("code", scope, state, forcelogin));
		System.out.println(oauth.authorize("code", scope, state));

		/*
		 * System.out.print("Hit enter when it's done.[Enter]:"); BufferedReader
		 * br = new BufferedReader(new InputStreamReader(System.in)); String
		 * code = br.readLine(); Log.logInfo("code: " + code);
		 * isAuthorized(oauth, code);
		 */

		// 测试发送微博
		/*
		 * Timeline tm = new Timeline();
		 * System.out.print("请输入所要发的微博的文本内容:[Enter]:"); br = new
		 * BufferedReader(new InputStreamReader(System.in)); String newStatus =
		 * br.readLine(); tm.UpdateStatus(newStatus);
		 */

		/*
		 * Timeline tm2 = new Timeline(); tm2.client.setToken(access_token);
		 * Status status = tm2.UpdateStatus("你好");
		 */

		// Forward_xl.upload(access_token, "图片", "image/winstart.jpg");

		return oauth;
	}

	public static Boolean isAuthorized(Oauth oauth, String code) {
		AccessToken accessToken = null;
		String access_token = "";
		Boolean is = false;
		try {
			accessToken = oauth.getAccessTokenByCode(code);
			access_token = accessToken.getAccessToken();
			System.out.println("已获得access_token：" + access_token);
			ConfigUtil.setValue("ACCESS_TOKEN", access_token);
			ConfigUtil.saveFile(FILE_PATH, null);
			is = true;
		} catch (WeiboException e) {
			if (401 == e.getStatusCode()) {
				Log.logInfo("Unable to get the access token.");
			} else {
				e.printStackTrace();
			}
		}

		String uid = accessToken.getUid();
		Users um = new Users();
		um.setToken(access_token);
		try {
			User user = um.showUserById(uid);
			// 获取当前用户的信息
			System.out.println("当前用户的名字：" + user.getName());
			ConfigUtil.setValue("USER_NAME", user.getName());
			ConfigUtil.saveFile(FILE_PATH, null);
			System.out.println("当前用户所发的微博数：" + user.getStatusesCount());
			System.out.println("当前用户关注数：" + user.getFriendsCount());
			System.out.println("当前用户粉丝数：" + user.getFollowersCount());
		} catch (WeiboException e) {
			e.printStackTrace();
		}

		return is;
	}

}
